import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login'
import AddGoods from '../components/Goods/AddGoods'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  // 使用懒加载
  {
    path: '/home',
    component: () => import('../views/Home'),
    children: [
      { path: '/home/', redirect: '/home/users' },
      { path: 'users', component: () => import('../components/User/User') },
      {
        path: 'categories',
        component: () => import('../components/Goods/Categories')
      },
      {
        path: 'goods',
        component: () => import('../components/Goods/Goods.vue')
      },
      { path: 'orders', component: () => import('../components/Order/Orders') },
      { path: 'params', component: () => import('../components/Goods/Params') },
      {
        path: 'reports',
        component: () => import('../components/Report/Reports')
      },
      { path: 'rights', component: () => import('../components/Right/Rights') },
      { path: 'roles', component: () => import('../components/Right/Roles') },
      {
        path: 'goods/add',
        component: () => import('../components/Goods/AddGoods')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫，beforeEach表示进入之前
router.beforeEach((to, from, next) => {
  // 如果要进入的是登录页面 则直接放行 这里的return主要是为了直接结束该函数
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果没有token就将跳转到登录页面  next可以传入参数
  /*
  * 1. next(false)：中断当前导航
  * 2. next('/')或者 next({path:'/'}) 跳转到这个地址
  * 3. next(error):导航被终止并且错误会被传递给router.onError() 注册过的回调。
  * */
  if (!tokenStr) return next('/login')
  // 如果上面一切正常就直接继续  不传入参数的就是执行下一个钩子，
  next()
})

export default router
